package com.duqc.sentinel;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName SentinelService
 * @Description TODO
 * @Author duqc
 * @Date 2021/5/17
 **/
@Slf4j
public class SentinelService {

    /**
     * 定义了资源 `HelloWorld` 每秒最多只能通过 20 个请求
     */
    private static void initFlowRules() {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("HelloWorld");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        //set limit QPS to 20
        rule.setCount(20);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }

    public static void main(String[] args) {
        initFlowRules();
        while (true) {
            Entry entry = null;
            try {
                entry = SphU.entry("HelloWorld");
                /*您的业务逻辑 - 开始*/
                log.info("hello-world");
                /*您的业务逻辑 - 结束*/
            } catch (Exception e) {
                /*流控逻辑处理 - 开始*/
                log.info("block!");
                /*流控逻辑处理 - 结束*/
            } finally {
                if (null != entry) {
                    entry.exit();
                }
            }
        }
    }


}
